package com.wekri.wechat4j.token;

import com.alibaba.fastjson.JSONObject;
import com.wekri.wechat4j.BaseMsg;
import com.wekri.wechat4j.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liuweiguo
 * @date 2019/1/28.
 */
public class Ticket extends BaseMsg {

    private static Logger logger = LoggerFactory.getLogger(Ticket.class);
    private static final String GET_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";


    private String access_token;
    private String ticket;

    public Ticket(String accessToken) {
        this.access_token = accessToken;
    }

    public String getTicket() {
        return ticket;
    }

    public boolean request() {
        String url = GET_TICKET_URL.replace("ACCESS_TOKEN", access_token);
        String result = HttpUtils.get(url);
        try {
            if (StringUtils.isBlank(result)) {
                return false;
            }
            if (!parseData(result)) {
                return false;
            }
        } catch (Exception e) {
            logger.error("", e);
            return false;
        }
        return true;
    }

    private boolean parseData(String result) {
        JSONObject json = JSONObject.parseObject(result);
        if ("0".equals(json.getString("errcode"))) {
            this.ticket = json.getString("ticket");
            return true;
        } else {
            return false;
        }
    }
}
